<?php
namespace app\index\controller;

use think\Controller;
use think\Validate;

class User extends Controller
{
    public $user_id;

    public function _initialize()
    {
        $user_id = is_login('user_id');
        if ($user_id) {
            $this->user_id = $user_id;
        } else {
            return $this->error('尚未登录，即将跳至登录页...', url('auth/login'));
        }
    }
    public function index()
    {
        $userinfo = model('UserInfo')->where('user_id', $this->user_id)->find();
        if (empty($userinfo)) {
            model('UserInfo')->insert(['user_id' => $this->user_id]);
            $userinfo = model('UserInfo')->where('user_id', $this->user_id)->find();
        }
        $userinfo->email = is_login('email');
        $userinfo->username = is_login('username');
        $page = ['title' => '用户中心 - 天佑二手货 - 天佑工作室'];
        return view('', ['userinfo' => $userinfo, 'page' => $page]);
    }

    /**
     * 修改昵称接口
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function modifyUserName()
    {
        $data = input('get.');
        // 字段验证
        $Validate = validate('User');
        if (!$Validate->scene('modify_username')->check($data)) {
            return $this->error($Validate->getError());
        }

        // 修改时间验证
        $user = model('User');
        $last_modifyname_time = $user->where('user_id', $this->user_id)->value('last_modifyname_time');
        if (time() <= strtotime('+6 Month', $last_modifyname_time)) {
            return $this->error('修改失败,6个月只能修改一次昵称');
        }

        // 数据写入
        $savedata = [
            'username' => $data['username'],
            'last_modifyname_time' => time(),
        ];
        // 用update方法不会自动刷新update字段 故改用save方法更新数据
        if ($user->save($savedata, ['user_id'=> $this->user_id]) === false) {
            return $this->error('修改失败,系统开小差了');
        }

        return $this->success('修改成功');
    }

    /**
     * 设置保密级别
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function setProtect()
    {
        $data = input('get.');
        $Validate = new Validate([
            'protect' => 'require|in:1,2,3,4',
        ]);
        if (!$Validate->check($data)) {
            return $this->error($Validate->getError());
        }
        if (model('UserInfo')->where('user_id', $this->user_id)->update(['protect' => $data['protect']]) > -1) {
            return $this->success('修改成功');
        }
        return $this->error('修改失败');
    }

    /**
     * 修改头像接口
     * @author cuibo weiai525@outlook.com at 2016-07-20 23:08:07
     */
    public function modifyImage()
    {
        $photo = input('photo', 'photo');
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $photo, $result)) {
            $base64 = str_replace($result[1], '', $photo);
            $image = base64_decode($base64);
            if ($image) {
                $imageInfo = getimagesizefromstring($image);
                if ($imageInfo[0] == $imageInfo[1] && $imageInfo[0] == 300 && in_array($imageInfo['mime'], ['image/png', 'image/jpg', 'image/bmp', 'image/jpeg']) && strlen($image) / 1024 / 1024 <= 2) {
                    $filename = md5($this->user_id) . '.' . substr($imageInfo['mime'], 6);
                    $path = ROOT_PATH . 'public' . DS . 'uploads' . DS . 'avatar' . DS;
                    if (!file_exists($path)) {
                        mkdir($path);
                    }
                    file_put_contents($path . $filename, $image);
                    model('userInfo')->where('user_id', $this->user_id)->update(['image' => $filename]);
                    return $this->success('头像修改成功');
                } else {
                    return $this->error('头像格式不对');
                }
            }
            return $this->error('头像格式不对');
        } else {
            return $this->error('头像格式不对');
        }
    }

    /**
     * 用户中心修改密码接口
     */
    public function modifyPassword()
    {

        if (request()->isPost()) {
            $data = input('post.');
            // 验证字段合法性
            $validate = validate('User');
            if ($validate->scene('modify_password')->check($data)) {
                /// 查找密码和邮箱
                $user = model('User')->where('user_id', $this->user_id)->field('password,email')->find();
                // 验证原始密码
                if ($user->password != password($user->email . $data['oldpassword'])) {
                    return $this->error("原始密码错误");
                }
                if (model('User')->save(['password' => password($user['email'] . $data['password'])],['user_id'=>$this->user_id]) === false) {
                    return $this->error('服务器出错，请重试');
                }
                // 修改成功则退出登录，暂定直接清除session，cookie，
                session('email', null);
                cookie('remember_token', null);
                return $this->success('密码修改成功！请重新登陆', url('auth/login'));
            } else {
                return $this->error($validate->getError());
            }
        }
    }
}
